<!-- 充值界面 -->
<template>
  <view class="page-container">
    <!-- 钱包卡片 -->
    <view class="header-box">
      <view class="card-box">
        <view class="card-head">
          <view class="card-title-row">
            <view class="card-title">钱包余额（元）</view>
            <view
              @tap="state.showMoney = !state.showMoney"
              class="eye-icon"
            >
              <text v-if="state.showMoney">👁</text>
              <text v-else>👁‍🗨</text>
            </view>
          </view>
        </view>
        <view class="balance-row">
          <view class="money-num">{{
            state.showMoney ? fen2yuan(userWallet.balance) : '*****'
          }}</view>
          <tui-button 
            width="120rpx" 
            height="60rpx" 
            :size="26" 
            type="danger"
            plain
            shape="circle"
            @click="goToRechargePage"
            class="recharge-btn">
            充值
          </tui-button>
        </view>
      </view>
    </view>

    <!-- 统计和筛选 -->
    <view class="filter-section">
      <view class="filter-box">
        <view class="date-picker-wrapper">
          <picker mode="date" :value="state.date[0]" @change="onDateChange">
            <view class="date-btn">
              <text>{{ dateFilterText }}</text>
              <text class="drop-icon">▼</text>
            </view>
          </picker>
        </view>
        <view class="total-box">
          <view class="total-item">总收入￥{{ fen2yuan(state.summary.totalIncome) }}</view>
          <view class="total-item">总支出￥{{ fen2yuan(state.summary.totalExpense) }}</view>
        </view>
      </view>
      
      <!-- 标签页 -->
      <view class="tabs-container">
        <view 
          class="tab-item" 
          v-for="(tab, index) in tabMaps" 
          :key="index"
          :class="{ 'tab-active': state.currentTab === index }"
          @tap="onTabChange(index)"
        >
          {{ tab.name }}
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="state.pagination.total === 0" class="empty-state">
      <view class="empty-icon-wrapper">
        <view class="empty-icon">
          <view class="doc-icon">📄</view>
          <view class="magnifier-icon">🔍</view>
        </view>
      </view>
      <text class="empty-text">暂无数据</text>
    </view>

    <!-- 钱包记录 -->
    <view v-if="state.pagination.total > 0" class="wallet-list-container">
      <view
        class="wallet-list-item"
        v-for="item in state.pagination.list"
        :key="item.id"
      >
        <view class="list-content">
          <view class="title-box">
            <text class="title">{{ item.title }}</text>
            <view class="money">
              <text v-if="item.price >= 0" class="add">+{{ fen2yuan(item.price) }}</text>
              <text v-else class="minus">{{ fen2yuan(item.price) }}</text>
            </view>
          </view>
          <text class="time">{{ formatTime(item.createTime) }}</text>
        </view>
      </view>
      
      <view class="load-more" v-if="state.loadStatus === 'more'">
        <text>上拉加载更多</text>
      </view>
      <view class="load-more" v-if="state.loadStatus === 'noMore'">
        <text>没有更多了</text>
      </view>
    </view>

  </view>
</template>

<script>
import dayjs from 'dayjs';
import { fen2yuan } from '@/common/lib/priceUtil.js';

export default {
  data() {
    return {
      userWallet: {
        balance: 0
      },
      state: {
        showMoney: true,
        date: [], // 筛选的时间段
        currentTab: 0,
        pagination: {
          list: [],
          total: 0,
          pageNo: 1,
          pageSize: 8,
        },
        summary: {
          totalIncome: 0,
          totalExpense: 0,
        },
        loadStatus: '',
        today: '',
      },
      tabMaps: [
        {
          name: '全部',
          value: '',
        },
        {
          name: '收入',
          value: '1',
        },
        {
          name: '支出',
          value: '2',
        },
      ],
    }
  },
  computed: {
    dateFilterText() {
      if (!this.state.date || this.state.date.length === 0) {
        return this.state.today;
      }
      if (this.state.date[0] === this.state.date[1]) {
        return this.state.date[0];
      } else {
        return this.state.date.join('~');
      }
    }
  },
  onLoad() {
    this.state.today = dayjs().format('YYYY-MM-DD');
    this.state.date = [this.state.today, this.state.today];
    
    // 获取钱包信息
    this.getWallet();
    // 获取钱包记录
    this.getLogList();
    // 获取统计信息
    this.getSummary();
  },
  onReachBottom() {
    if (this.state.loadStatus === 'noMore') {
      return;
    }
    this.state.pagination.pageNo++;
    this.getLogList();
  },
  methods: {
    // 分转元
    fen2yuan(price) {
      if (!price && price !== 0) return '0.00';
      return (Number(price) / 100).toFixed(2);
    },
    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return '';
      return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss');
    },
    // 获取钱包信息
    async getWallet() {
      try {
        const res = await this.$api.req("/pay/wallet/get", {}, "get", "JSON", false);
        if (res.code === 0) {
          this.userWallet = res.data || { balance: 0 };
        }
      } catch (error) {
        console.error('获取钱包信息失败', error);
      }
    },
    // 获得钱包记录分页
    async getLogList() {
      this.state.loadStatus = 'loading';
      try {
        const params = {
          pageNo: this.state.pagination.pageNo,
          pageSize: this.state.pagination.pageSize,
          type: this.tabMaps[this.state.currentTab].value,
          'createTime[0]': this.state.date[0] + ' 00:00:00',
          'createTime[1]': this.state.date[1] + ' 23:59:59',
        };
        
        const res = await this.$api.req("/pay/wallet-transaction/page", params, "get", "JSON", false);
        if (res.code === 0) {
          const data = res.data || {};
          const list = data.list || [];
          if (this.state.pagination.pageNo === 1) {
            this.state.pagination.list = list;
          } else {
            this.state.pagination.list = this.state.pagination.list.concat(list);
          }
          this.state.pagination.total = data.total || 0;
          this.state.loadStatus = this.state.pagination.list.length < this.state.pagination.total ? 'more' : 'noMore';
        }
      } catch (error) {
        console.error('获取钱包记录失败', error);
        this.state.loadStatus = 'noMore';
      }
    },
    // 获得钱包统计
    async getSummary() {
      try {
        // 参考 yudao-mall-uniapp 的实现，手动构建 query string
        const startTime = encodeURIComponent(this.state.date[0] + ' 00:00:00');
        const endTime = encodeURIComponent(this.state.date[1] + ' 23:59:59');
        const url = `/pay/wallet-transaction/get-summary?createTime=${startTime}&createTime=${endTime}`;
        
        const res = await this.$api.req(url, {}, "get", "JSON", false);
        if (res.code === 0) {
          this.state.summary = res.data || { totalIncome: 0, totalExpense: 0 };
        }
      } catch (error) {
        console.error('获取钱包统计失败', error);
      }
    },
    // 处理 tab 切换
    onTabChange(index) {
      this.state.currentTab = index;
      // 重新加载列表
      this.state.pagination.pageNo = 1;
      this.state.pagination.list = [];
      this.getLogList();
      this.getSummary();
    },
    // 处理日期选择
    onDateChange(e) {
      const selectedDate = e.detail.value;
      this.state.date = [selectedDate, selectedDate];
      // 重新加载列表
      this.state.pagination.pageNo = 1;
      this.state.pagination.list = [];
      this.getLogList();
      this.getSummary();
    },
    // 跳转到充值页面
    goToRechargePage() {
        uni.navigateTo({
        url: '/subPackage2/recharge/rechargePage'
        });
    },
  }
}
</script>

<style lang="scss" scoped>
  /* Sheep UI 样式已移除，使用自定义样式 */

  .page-container {
    min-height: 100vh;
    background: #f6f6f6;
  }

  /* 钱包卡片 */
  .header-box {
    background-color: #ffffff;
    padding: 30rpx;

    .card-box {
      width: 100%;
      min-height: 300rpx;
      padding: 40rpx;
      background: linear-gradient(180deg, var(--ui-BG-Main) 0%, var(--ui-BG-Main-gradient) 100%);
      border-radius: 30rpx;
      overflow: hidden;
      position: relative;
      z-index: 1;
      box-sizing: border-box;
      box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);

      /* 添加波浪背景效果 */
      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-image: 
          radial-gradient(circle at 20% 50%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
          radial-gradient(circle at 80% 80%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
          radial-gradient(circle at 40% 20%, rgba(255, 255, 255, 0.08) 0%, transparent 50%);
        pointer-events: none;
      }

      /* 底部波浪效果 */
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        height: 20rpx;
        background: linear-gradient(to bottom, transparent, rgba(255, 255, 255, 0.1));
        border-radius: 0 0 30rpx 30rpx;
        pointer-events: none;
      }

      .card-head {
        position: relative;
        z-index: 2;
        padding-top: 20rpx;
        margin-bottom: 40rpx;
      }

      .card-title-row {
        display: flex;
        align-items: center;
        justify-content: flex-start;
      }

      .card-title {
        font-size: 30rpx;
        font-weight: 500;
      }

      .eye-icon {
        font-size: 40rpx;
        color: #ffffff;
        cursor: pointer;
        margin-left: 20rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .balance-row {
        display: flex;
        align-items: center;
        justify-content: space-between;
        position: relative;
        z-index: 2;
      }

      .money-num {
        font-size: 70rpx;
        line-height: 70rpx;
        font-weight: 500;
        font-family: OPPOSANS, sans-serif;
      }

      .recharge-btn {
        /deep/ .tui-button {
          box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1) !important;
        }
      }
    }
  }

  /* 筛选区域 */
  .filter-section {
    background-color: #ffffff;
  }

  .filter-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 30rpx;
    background-color: #f6f6f6;

    .date-picker-wrapper {
      flex: 1;
    }

    .date-btn {
      display: inline-flex;
      align-items: center;
      background-color: #ffffff;
      line-height: 54rpx;
      border-radius: 27rpx;
      padding: 0 20rpx;
      font-size: 24rpx;
      font-weight: 500;
      color: #666666;
    }

    .drop-icon {
      font-size: 20rpx;
      color: #999999;
      margin-left: 10rpx;
    }

    .total-box {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      font-size: 24rpx;
      font-weight: 500;
      color: #999999;
    }

    .total-item {
      margin-bottom: 10rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
  }

  /* 标签页 */
  .tabs-container {
    display: flex;
    background-color: #ffffff;
    border-bottom: 1rpx solid #eeeeee;
  }

  .tab-item {
    flex: 1;
    text-align: center;
    padding: 30rpx 0;
    font-size: 28rpx;
    color: #666666;
    position: relative;

    &.tab-active {
      color: var(--ui-BG-Main);
      font-weight: 500;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 60rpx;
        height: 4rpx;
        background: var(--ui-BG-Main);
        border-radius: 2rpx;
      }
    }
  }

  /* 空状态 */
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 200rpx 0;
    background-color: #ffffff;

    .empty-icon-wrapper {
      width: 200rpx;
      height: 200rpx;
      margin-bottom: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
    }

    .empty-icon {
      position: relative;
      width: 120rpx;
      height: 120rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .doc-icon {
      font-size: 100rpx;
      color: #e0e0e0;
      opacity: 0.6;
      position: absolute;
      z-index: 1;
    }

    .magnifier-icon {
      font-size: 60rpx;
      color: #d0d0d0;
      opacity: 0.5;
      position: absolute;
      top: 20rpx;
      right: -10rpx;
      z-index: 2;
    }

    .empty-text {
      font-size: 28rpx;
      color: #999999;
    }
  }

  /* 钱包记录 */
  .wallet-list-container {
    background-color: #ffffff;
  }

  .wallet-list-item {
    padding: 30rpx;
    border-bottom: 1rpx solid #eeeeee;

    .list-content {
      display: flex;
      flex-direction: column;
    }

    .title-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 20rpx;
    }

    .title {
      font-size: 28rpx;
      color: #333333;
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .money {
      font-size: 28rpx;
      font-weight: bold;
      font-family: OPPOSANS, sans-serif;

      .add {
        color: var(--ui-BG-Main);
      }

      .minus {
        color: #333333;
      }
    }

    .time {
      color: #cccccc;
      font-size: 22rpx;
    }
  }

  .load-more {
    text-align: center;
    padding: 30rpx;
    font-size: 24rpx;
    color: #999999;
  }

</style>
